import { RouteRecordRaw } from "vue-router";
import API from "../api";

export const getVisibleMenus = (
  routes: Array<RouteRecordRaw>,
  currentUser: API.LoginUserVO | null
): Array<RouteRecordRaw> => {
  const visibleRoutes: Array<RouteRecordRaw> = [];

  const flattenRoutes = (routes: Array<RouteRecordRaw>) => {
    routes.forEach((route) => {
      // 检查父路由是否有 hideInMenu 属性并且为 true，如果是则跳过此路由及其子路由
      if (route.meta && route.meta.hideInMenu) {
        return;
      }

      // 检查权限
      if (route.meta && route.meta.access) {
        // 判断是否符合权限 如果是管理员那么就可以看见所有页面
        const hasAccess =
          currentUser?.userRole === route.meta.access ||
          currentUser?.userRole === "admin";
        if (!hasAccess) {
          return;
        }
      }

      // 如果没有子路由，并且没有 hideInMenu 或者 hideInMenu 为 false，则加入到列表中
      if (!route.children || (route.children && route.children.length === 0)) {
        if (!route.meta || !route.meta.hideInMenu) {
          visibleRoutes.push(route);
        }
      } else {
        // 递归处理子路由
        flattenRoutes(route.children);
      }
    });
  };

  flattenRoutes(routes);

  return visibleRoutes;
};
